//
//  WJNoticeManager.m
//  ows
//
//  Created by 王军 on 2017/8/22.
//  Copyright © 2017年 ows. All rights reserved.
//
/****
 使用:
 
 [[WJNoticeManager shareInstance] addOvserve:@"GET_INFO" callBack:^(NSString *) str]
 
 
 
 ****/


#import "WJNotificationManager.h"
#import "WJCommonUtils.h"

@interface WJNotificationManager ()

@property(strong,nonatomic)NSMutableDictionary *observerDictionary;
@property(strong,nonatomic)NSMutableArray *queueArray;
@property(strong,nonatomic)NSMutableArray *logArr;

@end


@implementation WJNotificationManager

/**
 *  单例
 *
 *  @return return value
 */
+(WJNotificationManager *)shareInstance{
    static WJNotificationManager*r_rootInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        r_rootInstance = [[WJNotificationManager alloc] init];
        [r_rootInstance initOptions];
    });
    return r_rootInstance;
}

-(void)initOptions {
    self.observerDictionary = [NSMutableDictionary new];
    self.queueArray = [NSMutableArray new];
    self.logArr = [NSMutableArray new];
}

-(void)addObserver:(id)target kName:(NSString *)kName object:(id)object callback:(void (^)(NSNotification *result))callback{
    [[NSNotificationCenter defaultCenter] addObserver:[WJNotificationManager shareInstance] selector:@selector(noticeAction:) name:kName object:object];
    NSString *objName = [NSString stringWithFormat:@"%s_%@", object_getClassName(target), kName];
    self.observerDictionary[objName] = [[NSMutableDictionary alloc] initWithObjectsAndKeys:target,@"target",
                                       kName,@"kName",
                                        objName,@"objName",
                                        [callback copy],@"callback",
                                       nil];
}

-(void)removeObserver:(id)target{
    NSArray *keys = self.observerDictionary.allKeys;
    for (NSString *key in keys) {
        NSDictionary *dic = self.observerDictionary[key];
        id itemTarget = dic[@"target"];
        if (itemTarget == target) {
            NSString *kName = dic[@"kName"];
            [self removeObserver:itemTarget kName:kName];
        }
    }
    [[NSNotificationCenter defaultCenter] removeObserver:target];
}

-(void)removeObserver:(id)target kName:(NSString *)kName {
    NSString *objName = [NSString stringWithFormat:@"%s_%@", object_getClassName(target), kName];
    [self.observerDictionary removeObjectForKey:objName];
    [[NSNotificationCenter defaultCenter] removeObserver:target name:kName object:nil];
}

-(void)noticeAction:(NSNotification *)sender{
    NSArray *keys = self.observerDictionary.allKeys;
    for (NSString *key in keys) {
        NSDictionary *dic = self.observerDictionary[key];
        NSString *kName = dic[@"kName"];
        if ([kName isEqualToString:sender.name]) {
            void (^block)(NSNotification *result) = dic[@"callback"];
            if (block){
                block(sender);
            }
        }
    }
}

-(void)sendNotification:(NSString *)kName{
    [self sendNotification:kName object:nil userInfo:nil];
}

// 发送通知，但是有延迟，0.5秒内没有重复的才会发送
-(void)sendNotification:(NSString *)kName debounce:(CGFloat)delay{
    BOOL exist = NO;
    NSTimeInterval lastSettingTime = [[NSDate date] timeIntervalSince1970];
    [self.logArr addObject:[NSString stringWithFormat:@"receive %@",[NSNumber numberWithDouble:lastSettingTime]]];
    for (NSMutableDictionary *item in self.queueArray) {
        if ([item[@"kName"] isEqualToString:kName]) {
            exist = YES;
            item[@"time"] = [NSNumber numberWithDouble:lastSettingTime];
        }
    }
    if (exist == NO) {
        NSMutableDictionary *item = [NSMutableDictionary new];
        item[@"time"] = [NSNumber numberWithDouble:lastSettingTime];
        item[@"kName"] = kName;
        [self.queueArray addObject:item];
    }
    [WJCommonUtils GCD_delay:delay b:^{
        NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
        for (NSMutableDictionary *item in self.queueArray) {
            if ([item[@"kName"] isEqualToString:kName]) {
                NSNumber *num = item[@"time"];
                if (nowTime - num.doubleValue > delay) {
                    [self sendNotification:kName object:nil userInfo:nil];
                    [self.queueArray removeObject:item];
                    [self.logArr addObject:[NSString stringWithFormat:@"send %@",[NSNumber numberWithDouble:nowTime]]];
                    break;
                }
            }
        }
    }];
}

-(void)sendNotification:(NSString *)kName object:(id)object userInfo:(NSDictionary *)userInfo{
    NSNotification * notice = [NSNotification notificationWithName:kName object:object userInfo:userInfo];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
}

@end
